package servlet;

import dao.MetaverseProductMapper;
import entity.MetaverseProduct;
import org.apache.ibatis.session.SqlSession;
import utils.MyBatisUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/metaverseProductAddServlet")
public class metaverseProductAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        SqlSession sqlSession=null;
        try {
            sqlSession=MyBatisUtil.createSqlSession();
            MetaverseProduct metaverseProduct = new MetaverseProduct();
            metaverseProduct.setName(request.getParameter("name"));
            metaverseProduct.setDesc(request.getParameter("desc"));
            metaverseProduct.setPrice(request.getParameter("price"));
            metaverseProduct.setFlag(Integer.parseInt(request.getParameter("flag")));
            int count=sqlSession.getMapper(MetaverseProductMapper.class).insert(metaverseProduct);
            sqlSession.commit();
            if(count>0){
                out.print("<script>alert('添加成功!');location='metaverseProductListServlet'</script>");
            }else{
                out.print("<script>alert('添加失败!');location='metaverseProductListServlet'</script>");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
